package com.cfm880.basicmessagepassing;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity{
    LooperThread mLooperThread;


    // Definition of the worker thread, acting as a consumer of the message queue;
    private static class LooperThread extends Thread{
        public Handler mHandler;

        @Override
        public void run() {
            // Associate a Looper—and implicitly a MessageQueue—with the thread.
            Looper.prepare();
            mHandler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 0){
                        doLongRunningOperation();
                    }
                }
            };
            Looper.loop();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLooperThread = new LooperThread();
        mLooperThread.start();
    }
    public void onClick(View v){
        if (mLooperThread.mHandler != null){
            Message msg = mLooperThread.mHandler.obtainMessage(0);
            mLooperThread.mHandler.sendMessage(msg);
        }
    }

    private void doLongRunningOperation(){
        // Add long running operation here
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
